! function(e) {
    "use strict";
    var n = function(e, r) {
        return n["string" == typeof r ? "compile" : "render"].apply(n, arguments)
    };
    n.version = "2.0.4", n.openTag = "<%", n.closeTag = "%>", n.isEscape = 0, n.isCompress = !1, n.parser = null, n.render = function(e, r) {
        var t = n.get(e) || i({
            id: e,
            name: "Render Error",
            message: "No Template"
        });
        return t(r)
    }, n.compile = function(e, t) {
        function a(r) {
            try {
                return new s(r, e) + ""
            } catch (o) {
                return u ? i(o)() : n.compile(e, t, !0)(r)
            }
        }
        var c = arguments,
            u = c[2],
            l = "anonymous";
        "string" != typeof t && (u = c[1], t = c[0], e = l);
        try {
            var s = o(e, t, u)
        } catch (p) {
            return p.id = e || t, p.name = "Syntax Error", i(p)
        }
        return a.prototype = s.prototype, a.toString = function() {
            return s.toString()
        }, e !== l && (r[e] = a), a
    };
    var r = n.cache = {},
        t = n.helpers = function() {
            var e = function(n, r) {
                    return "string" != typeof n && (r = typeof n, "number" === r ? n += "" : n = "function" === r ? e(n.call(n)) : ""), n
                },
                r = {
                    "<": "&#60;",
                    ">": "&#62;",
                    '"': "&#34;",
                    "'": "&#39;",
                    "&": "&#38;"
                },
                t = function(n) {
                    return e(n).replace(/&(?![\w#]+;)|[<>"']/g, function(e) {
                        return r[e]
                    })
                },
                i = Array.isArray || function(e) {
                    return "[object Array]" === {}.toString.call(e)
                },
                o = function(e, n) {
                    if (i(e))
                        for (var r = 0, t = e.length; t > r; r++) n.call(e, e[r], r, e);
                    else
                        for (r in e) n.call(e, e[r], r)
                };
            return {
                $include: n.render,
                $string: e,
                $escape: t,
                $each: o
            }
        }();
    n.helper = function(e, n) {
        t[e] = n
    }, n.onerror = function(n) {
        var r = "Template Error\n\n";
        for (var t in n) r += "<" + t + ">\n" + n[t] + "\n\n";
        e.console && console.error(r)
    }, n.get = function(t) {
        var i;
        if (r.hasOwnProperty(t)) i = r[t];
        else if ("document" in e) {
            var o = document.getElementById(t);
            if (o) {
                var a = o.value || o.innerHTML;
                i = n.compile(t, a.replace(/^\s*|\s*$/g, ""))
            }
        }
        return i
    };
    var i = function(e) {
            return n.onerror(e),
                function() {
                    return "{Template Error}"
                }
        },
        o = function() {
            var e = t.$each,
                r = "break,case,catch,continue,debugger,default,delete,do,else,false,finally,for,function,if,in,instanceof,new,null,return,switch,this,throw,true,try,typeof,var,void,while,with,abstract,boolean,byte,char,class,const,double,enum,export,extends,final,float,goto,implements,import,int,interface,long,native,package,private,protected,public,short,static,super,synchronized,throws,transient,volatile,arguments,let,yield,undefined",
                i = /\/\*[\w\W]*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|"(?:[^"\\]|\\[\w\W])*"|'(?:[^'\\]|\\[\w\W])*'|[\s\t\n]*\.[\s\t\n]*[$\w\.]+/g,
                o = /[^\w$]+/g,
                a = new RegExp(["\\b" + r.replace(/,/g, "\\b|\\b") + "\\b"].join("|"), "g"),
                c = /^\d[^,]*|,\d[^,]*/g,
                u = /^,+|,+$/g,
                l = function(e) {
                    return e.replace(i, "").replace(o, ",").replace(a, "").replace(c, "").replace(u, "").split(/^$|,+/)
                };
            return function(r, i, o) {
                function a(e) {
                    return m += e.split(/\n/).length - 1, n.isCompress && (e = e.replace(/[\n\r\t\s]+/g, " ").replace(/<!--.*?-->/g, "")), e && (e = x[1] + p(e) + x[2] + "\n"), e
                }

                function c(e) {
                    var r = m;
                    if ($ ? e = $(e) : o && (e = e.replace(/\n/g, function() {
                            return m++, "$line=" + m + ";"
                        })), 0 === e.indexOf("=")) {
                        var i = !/^=[=#]/.test(e);
                        if (e = e.replace(/^=[=#]?|[\s;]*$/g, ""), i && n.isEscape) {
                            var a = e.replace(/\s*\([^\)]+\)/, "");
                            t.hasOwnProperty(a) || /^(include|print)$/.test(a) || (e = "$escape(" + e + ")")
                        } else e = "$string(" + e + ")";
                        e = x[1] + e + x[2]
                    }
                    return o && (e = "$line=" + r + ";" + e), u(e), e + "\n"
                }

                function u(n) {
                    n = l(n), e(n, function(e) {
                        e && !y.hasOwnProperty(e) && (s(e), y[e] = !0)
                    })
                }

                function s(e) {
                    var n;
                    "print" === e ? n = T : "include" === e ? (v.$include = t.$include, n = O) : (n = "$data." + e, t.hasOwnProperty(e) && (v[e] = t[e], n = 0 === e.indexOf("$") ? "$helpers." + e : n + "===undefined?$helpers." + e + ":" + n)), w += e + "=" + n + ","
                }

                function p(e) {
                    return "'" + e.replace(/('|\\)/g, "\\$1").replace(/\r/g, "\\r").replace(/\n/g, "\\n") + "'"
                }
                var f = n.openTag,
                    d = n.closeTag,
                    $ = n.parser,
                    g = i,
                    h = "",
                    m = 1,
                    y = {
                        $data: 1,
                        $id: 1,
                        $helpers: 1,
                        $out: 1,
                        $line: 1
                    },
                    v = {},
                    w = "var $helpers=this," + (o ? "$line=0," : ""),
                    b = "".trim,
                    x = b ? ["$out='';", "$out+=", ";", "$out"] : ["$out=[];", "$out.push(", ");", "$out.join('')"],
                    E = b ? "$out+=$text;return $text;" : "$out.push($text);",
                    T = "function($text){" + E + "}",
                    O = "function(id,data){data=data||$data;var $text=$helpers.$include(id,data,$id);" + E + "}";
                e(g.split(f), function(e) {
                    e = e.split(d);
                    var n = e[0],
                        r = e[1];
                    1 === e.length ? h += a(n) : (h += c(n), r && (h += a(r)))
                }), g = h, o && (g = "try{" + g + "}catch(e){" + "throw {" + "id:$id," + "name:'Render Error'," + "message:e.message," + "line:$line," + "source:" + p(i) + ".split(/\\n/)[$line-1].replace(/^[\\s\\t]+/,'')" + "};" + "}"), g = w + x[0] + g + "return new String(" + x[3] + ");";
                try {
                    var S = new Function("$data", "$id", g);
                    return S.prototype = v, S
                } catch (P) {
                    throw P.temp = "function anonymous($data,$id) {" + g + "}", P
                }
            }
        }();
    "function" == typeof define ? define(function() {
        return n
    }) : "undefined" != typeof exports && (module.exports = n), e.template = n
}(this);
template.helper('dateFormat', function(date, format) {
    date = new Date((date || "").replace(/-/g, "/"));
    var map = {
        "M": date.getMonth() + 1, //月份
        "d": date.getDate(), //日
        "h": date.getHours(), //小时
        "m": date.getMinutes(), //分
        "s": date.getSeconds(), //秒
        "q": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
        var v = map[t];
        if (v !== undefined) {
            if (all.length > 1) {
                v = '0' + v;
                v = v.substr(v.length - 2);
            }
            return v;
        } else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
        }
        return all;
    });
    return format;
});
(function($) {
    template.helper('dateFormat', function(date, format) {
        date = new Date((date || "").replace(/-/g, "/"));
        var map = {
            "M": date.getMonth() + 1, //月份
            "d": date.getDate(), //日
            "h": date.getHours(), //小时
            "m": date.getMinutes(), //分
            "s": date.getSeconds(), //秒
            "q": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
            var v = map[t];
            if (v !== undefined) {
                if (all.length > 1) {
                    v = '0' + v;
                    v = v.substr(v.length - 2);
                }
                return v;
            } else if (t === 'y') {
                return (date.getFullYear() + '').substr(4 - all.length);
            }
            return all;
        });
        return format;
    });
    $.util = {
        cookie: function(name, value, options) {
            if (typeof value != 'undefined') {
                options = options || {};
                if (value === null) {
                    value = '';
                    options.expires = -1;
                }
                var expires = '';
                if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                    var date;
                    if (typeof options.expires == 'number') {
                        date = new Date();
                        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                    } else {
                        date = options.expires;
                    }
                    expires = '; expires=' + date.toUTCString();
                }
                var path = options.path ? '; path=' + options.path : '';
                var domain = options.domain ? '; domain=' + options.domain : '';
                var secure = options.secure ? '; secure' : '';
                document.cookie = [name, '=', value, expires, path, domain, secure].join('');
            } else {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = $.trim(cookies[i]);
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
        },
        page: {
            getWidth: function() {
                var doc = document,
                    body = doc.body,
                    html = doc.documentElement,
                    client = doc.compatMode == 'BackCompat' ? body : doc.documentElement;
                return Math.max(html.scrollWidth, body.scrollWidth, client.clientWidth);
            },
            getHeight: function() {
                var doc = document,
                    body = doc.body,
                    html = doc.documentElement,
                    client = doc.compatMode == 'BackCompat' ? body : doc.documentElement;
                return Math.max(html.scrollHeight, body.scrollHeight, client.clientHeight);
            },
            getViewWidth: function() {
                var doc = document,
                    client = doc.compatMode == 'BackCompat' ? doc.body : doc.documentElement;
                return client.clientWidth;
            },
            getViewHeight: function(doc) {
                var doc = document || doc,
                    client = doc.compatMode == 'BackCompat' ? doc.body : doc.documentElement;
                return client.clientHeight;
            }
        },
        getUa: function() {
          var ua = navigator.userAgent.toLowerCase();
          if (ua.match(/MicroMessenger/i) == "micromessenger") {
            return 'weixin'
          } else if (ua.match(/nativeApp/i) == "nativeapp") {
            return 'nativeApp'
          } else {
            return 'normal'
          }
        },
        getParam: function(o) {
            var reg = new RegExp(
                "(^|\\?|&|#)" + o + "=([^&#]*)(&|\x24|#)",
                "");
            url = location.href,
                match = url.match(reg);
            if (match) {
                return decodeURIComponent(match[2]);
            }
            return null;
        },
        getParamByObject: function(o) {
            var params = decodeURIComponent(this.getParam("params"));
            if (params) {
                params = JSON.parse(params);
                if (params[o]) {
                    return params[o];
                }
            }
            return null;
        },
        getParamAsObject: function() {
            var params = decodeURIComponent(this.getParam("params"));
            if (params) {
                params = JSON.parse(params);
                return params;
            }
            return null;
        },
        ok: function(msg, onok, oncancel, skin, width, height) {
            $.dialog({
                content: msg || "",
                skin: skin || "white",
                title: "alert",
                titleText: "提示",
                width: width,
                height: height,
                ok: function() {
                    onok && onok();
                },
                cancel: function() {
                    oncancel && oncancel();
                }
            });
        },
        showMsg: function(msg, onok, skin) {
            $.dialog({
                content: msg || "",
                skin: skin || "white",
                title: "alert",
                titleText: "提示",
                ok: function() {
                    onok && onok();
                }
            });
        },
        next: function(msg, onok, skin,sure) {
            $.dialog({
                content: msg || "",
                skin: skin || "white",
                title: "alert",
                titleText: "提示",
                ok: function() {
                    onok && onok();
                },
                sure:sure
            });
        },
        alert: function(msg) {
            $.dialog({
                skin: "time",
                content: msg || "",
                time: 1000,
                titleText: "提示"
            });
        },
        openLayer: function(option) {
    			var html = '<div id="layer">'
    				+ '<div class="bg"></div>'
    				+ '<div class="layer-box">'
    					+ '<i class="iconfont">' + option.iconfont + '</i>'
    					+ '<div class="title">' + option.title + '</div>'
    					+ '<div class="discript">' + option.discript + '</div>'
    				+ '</div>'
    			+ '</div>'
    			$('body').append(html);
    			setTimeout(function(){
            $('#layer').remove();
    			},1000);
    		},
        //遮罩层
        mask: function(bgColor,index,opacity){
            var mask = document.createElement('div');
            mask.id='mask';
            var strStyle='width:100%;height:'+$(window).height()+'px;position:fixed;top:0;background-color:'+bgColor+';' +
                'opacity:'+opacity+';background-position:center center;background-size: 100% 100%;z-index:'+index;
            mask.style.cssText=strStyle;
            document.body.appendChild(mask);
            return mask;
        },
        imgCenter: function(img) {
            var me = this;
            var parHeight = $(img).parent().height();
            var top = (parHeight - $(img).height()) / 2;
            if (top) {
                $(img).css({
                    "marginTop": top + 'px'
                });
            }
        },
        imgZoom: function(img, zoomWidth, zoomHeight) {
            var me = this;
            var parWidth = $(img).parent().width();
            if (zoomWidth.indexOf("%") >= 0) {
                zoomWidth = zoomWidth.substr(0, zoomWidth.length - 1);
                zoomWidth = parWidth * zoomWidth / 100;
            }
            var prop = me._setZoom($(img).width(), $(img).height(), zoomWidth, zoomHeight);
            if (prop) {
                $(img).css({
                    "width": prop.w + 'px',
                    "height": prop.h + 'px',
                    "marginTop": prop.hp + 'px'
                });
            }
        },
        //浮点数加
        accAdd:function(arg1, arg2) {
           var r1, r2, m, c;
           try {
               r1 = arg1.toString().split(".")[1].length;
           }
           catch (e) {
               r1 = 0;
           }
            try {
                r2 = arg2.toString().split(".")[1].length;
            }
            catch (e) {
                r2 = 0;
            }
            c = Math.abs(r1 - r2);
            m = Math.pow(10, Math.max(r1, r2));
            if (c > 0) {
                var cm = Math.pow(10, c);
                if (r1 > r2) {
                    arg1 = Number(arg1.toString().replace(".", ""));
                    arg2 = Number(arg2.toString().replace(".", "")) * cm;
                } else {
                    arg1 = Number(arg1.toString().replace(".", "")) * cm;
                    arg2 = Number(arg2.toString().replace(".", ""));
                }
            } else {
                arg1 = Number(arg1.toString().replace(".", ""));
                arg2 = Number(arg2.toString().replace(".", ""));
            }
            return (arg1 + arg2) / m;
        },
        //浮点数减
        accSub:function(arg1, arg2) {
            var r1, r2, m, n;
            try {
                r1 = arg1.toString().split(".")[1].length;
            }
            catch (e) {
                r1 = 0;
            }
            try {
                r2 = arg2.toString().split(".")[1].length;
            }
            catch (e) {
                r2 = 0;
            }
            m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
            n = (r1 >= r2) ? r1 : r2;
            return ((arg1 * m - arg2 * m) / m).toFixed(n);
        },
        //浮点数乘
        accMul:function(arg1, arg2) {
            var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
           try {
               m += s1.split(".")[1].length;
           }
           catch (e) {
           }
            try {
                m += s2.split(".")[1].length;
            }
            catch (e) {
            }
            return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
        },
        //浮点数除
        accDiv:function(arg1, arg2) {
            var t1 = 0, t2 = 0, r1, r2;
            try {
                t1 = arg1.toString().split(".")[1].length;
            }
            catch (e) {}
            try {
                t2 = arg2.toString().split(".")[1].length;
            }
            catch (e) {}
            with (Math) {
                r1 = Number(arg1.toString().replace(".", ""));
                r2 = Number(arg2.toString().replace(".", ""));
                return (r1 / r2) * pow(10, t2 - t1);
            }
        },
        /**
         * [_setZoom 图片缩放]
         * @param {[type]} realWidth [description]
         * @param {[type]} realHeight [description]
         * @param {[type]} zoomWidth [description]
         * @param {[type]} zoomHeight [description]
         * @return {[type]}   [description]
         */
        _setZoom: function(realWidth, realHeight, zoomWidth, zoomHeight) {
            var wRadio,
                hRadio,
                radio;
            if (realWidth && realHeight) {
                if (realWidth < zoomWidth && realHeight < zoomHeight) {
                    return {
                        w: realWidth,
                        h: realHeight,
                        hp: ((zoomHeight - realHeight) / 2)
                    }
                }
                wRadio = zoomWidth / realWidth;
                hRadio = zoomHeight / realHeight;
                radio = wRadio <= hRadio ? wRadio : hRadio;
                return {
                    w: Math.ceil(realWidth * radio),
                    h: Math.ceil(realHeight * radio),
                    hp: Math.ceil(((zoomHeight - realHeight * radio) / 2))
                }
            }
            return null;
        },
        pageLoading: {
            show: function(msg) {
                var pageLoading = $("#pageLoading");
                var mask = $("#loadingMask");
                var msg = msg || "正在加载";
                var maxHeight = $.util.page.getHeight();
                if (pageLoading.size() > 0) {
                    mask.show();
                    pageLoading.show().find(".msg").html(msg);
                } else {
                    $("body").append(
                        "<div class='page-loading' id='pageLoading'>" +
                        "<div class='msg'>" + msg + "</div>" +
                        "</div>" +
                        "<div class='loading-mask' id='loadingMask'></div>"
                    );
                    $("#loadingMask").css("height",maxHeight).show();
                }
            },
            hide: function() {
                $("#pageLoading").hide();
                $("#loadingMask").hide();
            }
        },
        dataLoading: {
            show: function(msg) {
                var dataLoading = $("#dataLoading");
                var msg = msg || "加载中";
                if (dataLoading.size() > 0) {
                    dataLoading.show();
                } else {
                    $("body").append(
                        "<div class='data-loading' id='dataLoading'>" +
                        "<div class='out'>" +
                        "<div class='loading'></div>" +
                        "<div class='msg'>" + msg + "</div>" +
                        "</div>" +
                        "</div>"
                    );
                }
            },
            hide: function() {
                $("#dataLoading").hide();
            }
        },
        dataEnd: {
            show: function(msg) {
                var dataEnd = $("#dataEnd");
                var msg = msg || "没有更多了";
                if (dataEnd.size() > 0) {
                    dataEnd.show();
                } else {
                    $("body").append(
                        "<div class='data-end' id='dataEnd'>" +
                        msg +
                        "</div>"
                    );
                }
            },
            hide: function() {
                $("#dataEnd").hide();
            }
        },
        loadingState: "loaded",
        initDataLoading: function(obj) {
            var util = this;
            var offsetY = 0;
            var offsetYY = 0;
            if ($.os.ios) {
                $(document).on("touchstart", function(e) {
                    offsetY = e.touches[0].pageY;
                    offsetYY = offsetY;
                });
                $(document).on("touchmove", function(e) {
                    offsetYY = e.touches[0].pageY;
                });
                $(document).on("touchend", function(e) {
                    if (Math.abs(offsetYY - offsetY) > 5) {
                        loadHandler();
                    }
                });
            } else {
                $(window).on("scroll", function(e) {
                    loadHandler();
                });
            }

            function loadHandler() {
                var me = obj.me;
                var topDis = document.body.scrollTop || document.documentElement.scrollTop,
                    viewHeight = $.util.page.getViewHeight(),
                    lastChildren = obj.lastChildren(),
                    coords = lastChildren.length > 0 && lastChildren[0].getBoundingClientRect(),
                    offset = 0;
                if (coords.top - offset < viewHeight && util.state != "loading") {
                    var page = obj.page() || 0;
                    var pageCount = obj.pageCount();
                    util.state = "loading";
                    if (parseInt(page, 10) < parseInt(pageCount, 10) - 1) {
                        $.util.dataLoading.show();
                        window.scroll(0, document.body.scrollHeight);
                        me._loadList(++page, function() {
                            util.state = "loaded";
                            $.util.dataLoading.hide();
                        });
                    } else {
                        util.state = "loaded";
                        $.util.dataEnd.show();
                    }
                }
            }
        }
    }
    $.req = {
        get: function(url, params, successHandler, errorHandler) {
            var me = this;
            $.ajax({
                url: me._getReqUrl(url),
                type: "get",
                dataType: "json",
                data: me._getReqParams(params),
                success: function(data) {
                    successHandler && successHandler(data);
                },
                error: function(data) {
                    errorHandler && errorHandler(data);
                }
            });
        },
        post: function(url, params, successHandler, errorHandler) {
            var me = this;
            $.ajax({
                url: me._getReqUrl(url),
                type: "post",
                dataType: "json",
                data: me._getReqParams(params),
                success: function(data) {
                    successHandler && successHandler(data);
                },
                error: function() {
                    errorHandler && errorHandler(data);
                }
            });
        },
        _getReqParams: function(params) {
            var newP = {};
            for (var n in params) {
                if (n == "params") {
                    newP[n] = JSON.stringify(params[n]);
                } else {
                    newP[n] = params[n];
                }
            }
            return newP;
        },
        _getReqUrl: function(url) {
            url = baseUrl + url;
            return url;
        }
    }
})($);
/**验证规则类*/
function ValideRule() {
    var me = this;

    /**验证规则定义*/

    this._rules = {
        required: function(val) {
            return !!(val && !/^(?:\s|\u3000)+$/.test(val));
        },
        email: "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$",
        mobile: "(^(13|15|17|16|18)[0-9]{9}$)",
        tel: "^(([0\\+]\\d{2,3}-)?(0\\d{2,3})-)?(\\d{7,8})(-(\\d{3,}))?$",
        url: "^http[s]?:\\/\\/\.*$",
        username: "^\\w+$",
        number: "^\\d+$",
        num: "^([+-]?)\\d*\\.?\\d+$", //数字
        num1: "^[1-9]\\d*|0$", //正数（正整数 + 0）
        num2: "^-[1-9]\\d*|0$", //负数（负整数 + 0）
        intege: "^-?[1-9]\\d*$",
        intege1: "^[1-9]\\d*$",
        positiveDecimal: "/^[\+]?\d*(\.\d+)?$/",
        decmal: "^[0-9]\\d*(\\.\\d{1,2})?$", //正浮点数
        decmal2: "^[0-9]\\d*(\\.\\d{1,2})?$", //正浮点数
        name: "",
        maxlength: function(val, opt) {
            return me.__getByteLength(val) <= opt;
        },
        minlength: function(val, opt) {
            return me.__getByteLength(val) >= opt;
        },
        rangelength: function(val, opt) {
            return val.length >= opt[0] && val.length <= opt[1];
        },
        equal: function(val, opt) {
            return val === (typeof opt == "function" ? opt() : opt);
        }
    };
}
ValideRule.prototype = {
        __getRule: function(name) {
            return this._rules[name];
        },
        __getByteLength: function(str) {
            var len = 0;
            for (var i = 0; i < str.length; i++) {
                if (str.charCodeAt(i) >= 0x4e00 && str.charCodeAt(i) <= 0x9fa5) {
                    len += 2;
                } else {
                    len++;
                }
            }
            return len;
        },
        /**添加一个验证规则*/
        addRule: function(name, handler) {
            this._rules[name] = handler;
        },
        __match: function(name, val, callback, opt) {
            var me = this,
                rule = me.__getRule(name),
                param = opt && opt.param;

            if (typeof param == "function") {
                callback(param(val));
            } else {
                if (typeof rule == "function") {
                    callback(rule(val, param));
                } else {
                    callback(new RegExp(rule).test(val));
                }

            }
        }
    }
    /**
    验证类
    formId 要验证的表单,
    ruleConfig 验证规则配置,
    opt 其他配置
    */

function Validate(formId, ruleConfig, opt) {
    var me = this;
    this._form = $("#" + formId)[0];
    this._fieldRule = ruleConfig;
    this._validRule = new ValideRule();

    this._opt = $.extend({
        submitForm: false,
        /**是否自动提交表单*/
        mesErrorClassName: "mes_error",
        mesNormalClassName: "mes_show",
        errorClassName: "va_error",
        /**验证出错文本框样式*/
        focusClassName: "va_focus",
        /**鼠标点击激活样式*/
        showDialog: 1
    }, opt);

    if (!this._fieldRule) return;
    if (!this._form) return;

    $.each(me._fieldRule, function(item, val) {
        var $item = $("#" + item),
            show = val.show || "",
            def = val.def,
            defColor = "#333";

        if ($item[0]) {
            val.messageContainer = me.createMessageContainer($item, val);
            if (!val.focus) {
                $item.bind("blur", function() {
                    me.__validateField(item);
                });
                $item.bind("focus", function() {
                    var elems = $("." + me._opt.focusClassName, me._form);
                    elems.removeClass(me._opt.focusClassName)
                    $item.removeClass(me._opt.errorClassName).addClass(me._opt.focusClassName);
                    $("#" + val.messageContainer).html(show)
                        .removeClass(me._opt.mesErrorClassName)
                        .addClass(me._opt.mesNormalClassName);
                    if (!show) {
                        $("#" + val.messageContainer).hide();
                    }
                });
            }
        }
    });
}
Validate.prototype = {
    getValidRule: function() {
        return this._validRule;
    },
    addRule: function(va, name, func) {
        this._validRule.addRule(name, function() {
            func && func();
        });
    },
    rePos: function(obj, mesContainer, val) {
        var pos = val.pos || "right",
            offset = obj.position(),
            offsetX = val.offsetX || 0,
            offsetY = val.offsetY || 0,
            x = val.x,
            y = val.y,
            posX,
            posY;
        if (val.positionId) {
            offset = $("#" + val.positionId).position();
        }
        if (pos === "right") {
            if (x && y) {
                posX = x;
                posY = y;
            } else {
                posY = offset.top + offsetY;
                posX = offset.left + obj.width() + 10 + offsetX;
            }
            mesContainer.css({
                "top": offset.top + offsetY + 'px',
                "left": offset.left + obj.width() + 10 + offsetX + 'px'
            });
        }
        if (pos === "bottom") {
            if (x && y) {
                posX = x;
                posY = y;
            } else {
                posY = offset.top + obj.height() + offsetY;
                posX = offset.left + offsetX;
            }
        }
        mesContainer.css({
            "left": posX + 'px',
            "top": posY + 'px'
        });
    },
    createMessageContainer: function(obj, val) {
        var pos = val.pos || "right",
            opt = this._opt,
            def = val.def || "",
            show = val.show || "",
            mesContainer = $("<div style='position:absolute;z-index:999'></div>"),
            tipid = obj.attr("id") + 'Tip';
        mesContainer.addClass(opt.mesNormalClassName)
            .html(show)
            .attr("id", tipid);

        obj.after(mesContainer);

        this.rePos(obj, mesContainer, val);

        if (show) {
            mesContainer.show();
        } else {
            mesContainer.hide();
        }
        return tipid;
    },

    /***
    对表单的所有控件进行验证
    callback 验证完成后回调
    */
    validate: function(callback) {
        var me = this,
            keyList = me._fieldRule,
            resultList = [];
        $.each(keyList, function(item, val) {

            if ($("#" + item).size() > 0) {

                me.__validateField(item, function(val, list) {

                    if (list.length > 0) {
                        resultList = resultList.concat(list.shift());

                    }

                });

            }

        });
        if (resultList.length == 0) {
            if (this._opt.submitForm) {
                $(me._form).submit();
            }
        } else {
            var offset = $("#" + resultList[0].field).offset();
        }
        typeof callback == "function" && callback(resultList.length <= 0, resultList);
    },

    /**
    验证单个控件
    */

    __validateField: function(name, callback) {
        var me = this,
            fieldRule = me._fieldRule[name],
            rule = me._fieldRule[name].rule,
            $elem = $("#" + name),
            value = $elem.val(),
            entry, resultList = [],
            messageContainer = me._fieldRule[name]["messageContainer"];
        if (messageContainer) {
            messageContainer = $("#" + messageContainer);
        }
        $.each(rule, function(item, val) {

            entry = rule[item];
            if (fieldRule.def === value) {
                value = "";
            }
            me._validRule.__match(item, value, function(rs) {
                if (!rs) {
                    var message = entry.message;
                    if (typeof message == "function") {
                        message = message();
                    }
                    resultList.push({
                        type: item,
                        field: name,
                        result: rs,
                        message: entry.message
                    });

                }
            }, {
                param: entry.hasOwnProperty('param') ? entry.param : entry
            });
        });
        if (resultList.length <= 0) {
            $elem.removeClass(this._opt.errorClassName).removeClass(me._opt.focusClassName);
            if (messageContainer) {
                messageContainer.hide().html("")
                    .removeClass(this._opt.mesNormalClassName)
                    .addClass(this._opt.mesErrorClassName);
            }
        } else {
            $elem.removeClass(this._opt.focusClassName).addClass(this._opt.errorClassName);
            if (messageContainer) {
                if (resultList.length > 0) {
                    var result = resultList[0];
                    messageContainer.removeClass(this._opt.mesNormalClassName)
                        .addClass(this._opt.mesErrorClassName)
                        .show()
                        .html(result.message);
                    me.rePos($elem, messageContainer, fieldRule);
                }
            }
        }
        typeof callback == "function" && callback(resultList.length <= 0, resultList);
    }
};
